package me.eg.first;

/**
 * 641. 设计循环双端队列
 *
 * https://leetcode-cn.com/problems/design-circular-deque
 */
public class MyCircularDeque {
    /**
     用环形数组实现
     */
    private int[] elements;
    private int size;
    private int head; // 头指针
    private int tail; // 尾指针
    private boolean isEmpty; // 是否空队列

    public MyCircularDeque(int k) {
        size = k;
        elements = new int[size];
        head = 0; // 设置头指针
        tail = 0; // 设置尾指针
        isEmpty = true;
    }

    public boolean insertFront(int value) {
        if (isFull()) return false;
        // 对头添加元素 head -= 1;
        head = (head + size - 1) % size;
        elements[head] = value;
        isEmpty = false;
        return true;
    }

    public boolean insertLast(int value) {
        // 队尾添加元素 tail += 1;
        // 队列满，返回false
        if (isFull()) return false;
        elements[tail] = value;
        tail = (tail + 1) % size;
        isEmpty = false;
        return true;
    }

    public boolean deleteFront() {
        // 队头删除元素 head += 1;
        if (isEmpty()) return false;
        head = (head + 1) % size;
        if (head == tail) isEmpty = true;
        return true;
    }

    public boolean deleteLast() {
        // 队尾删除元素 tail -= 1；
        if (isEmpty()) return false;
        tail = (tail + size - 1) % size;
        if (head == tail) isEmpty = true;
        return true;
    }

    public int getFront() {
        if (isEmpty()) return -1;
        else return elements[head];
    }

    public int getRear() {
        if (isEmpty()) return -1;
        else return elements[(tail + size -1) % size];
    }

    public boolean isEmpty() {
        return isEmpty;
    }

    public boolean isFull() {
        return !isEmpty && head == tail;
    }
}
